import QtQuick 1.1
import com.nokia.meego 1.0
import "HarmattanUIConstants.js" as Constants

Page {
    id: fileManagementPage

    property bool loadMode: true // If false, save mode is enabled
    property string filename: "Untitled" // Holds the filename of the current gesture set
    property string fullPath: "" // Holds the full path to the current gesture set file

    /**
     * Loads a file with the given path.
     *
     * @param filePath The path to the file to load.
     */
    function loadFile(filePath) {
        engine.clearModels();
        fullPath = helper.ensurePathValidity(filePath);
        console.debug("FileManagementPage.qml: loadFile(): Will try to load from", fullPath);
        storageThread.loadByUrl(fullPath);
        filename = helper.extractFilenameFromPath(filePath);
    }

    /**
     * Saves the current set to the given path.
     *
     * @param filePath The path where to save.
     */
    function saveFile(filePath) {
        fullPath = helper.ensurePathValidity(filePath);
        console.debug("FileManagementPage.qml: saveFile(): Will try to save to", filePath);
        helper.saveGestures(fullPath, engine);
        filename = helper.extractFilenameFromPath(fullPath);
    }

    // Controls for changing the path and if in save mode, contains the field
    // where to insert the filename and a save button.
    FolderListControl {
        id: folderListControl

        anchors {
            top: parent.top
            left: parent.left
            right: parent.right
        }

        z: 1
        showFileControl: !loadMode
        currentFolder: helper.urlToLocalFile(folderList.folder)
        filename: fileManagementPage.filename

        onParentFolderRequested: folderList.toParentFolder()

        onSaveRequested: {
            var filePath = folderList.folder + '/' + filename;
            fileManagementPage.saveFile(filePath);
        }
    }

    // The actual folder list
    FolderList {
        id: folderList

        anchors {
            top: folderListControl.bottom
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }

        defaultPath: storageManager.defaultPath()
        scrollDecorator: ScrollDecorator { flickableItem: folderList.modelView }

        onFileSelected: {
            fileManagementPage.filename = file;

            if (loadMode) {
                loadFile(file);
            }
            else {
                saveFile(file);
            }

            pageStack.pop();
        }
    }

    // Tool bar
    tools: ToolBarLayout {
        ToolIcon {
            iconId: "toolbar-back"
            onClicked: pageStack.pop();
        }
    }
}

// End of file.
